// 问卷调查
import React, { useReducer, useState } from "react";
// import { useSelector } from "react-redux";
import { store } from "../../store/index";
import queryApi from "../../api/query";
import { serverUrl } from "../../api/query";

import * as XLSX from "xlsx";
import * as FileSystem from "expo-file-system";
import * as Sharing from "expo-sharing";
import * as Clipboard from "expo-clipboard";
import { Alert } from "react-native";

const OpinionsContext = React.createContext();

const typeOptions = [
  "一般脱贫户",
  "脱贫不稳定户",
  "突发困难严重户1",
  "突发困难严重户2",
  "边缘易致贫户",
  "其他户",
  "全部",
];

const dataReducer = (state, action) => {
  switch (action.type) {
    case "edit_state":
      return state.map((preQues, quesIndex) => {
        return quesIndex == action.payload.quesIndex
          ? action.payload.Ques
          : preQues;
      });
    case "edit_opinions":
      return state.map((ques, index) => {
        return index == action.payload.quesIndex
          ? {
              ...ques,
              opinions: action.payload.opinions,
            }
          : ques;
      });
    case "get_ques":
      // console.log(action.payload.myquesArr[0].title);
      return action.payload.myquesArr;
    default:
      return state;
  }
};

// let newQuesData = {
//   target: -1, // 0：一般户
//   title: "",
//   state: -1,
//   group: "",
//   time: "",
//   user: "",
//   image: [],
//   video: [],
//   soundfile: [],
//   userproblem: "",
//   body: [],
//   opinions: "",
// };

let initData = [];

export const OpinionsProvider = ({ children }) => {
  const [GroupQuesData, dispatch] = useReducer(dataReducer, initData);
  const [opinionsLoading, setOpinionsLoading] = useState("end");
  const [villageArr, setVillageArr] = useState(["全部"]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(30);
  const [pageLen, setPageLen] = useState(0);

  // 管理员查找本组的问卷，审核员查找全部的问卷
  const getGroupQues = async (pageIndex) => {
    setOpinionsLoading("ing");
    console.log("页码---", pageIndex);
    const user = store.getState().authR.user;
    try {
      let data;
      if (user.role == "admin") {
        data = await queryApi.get(
          "userques/bygrouppage/" +
            user.group +
            "?page=" +
            pageIndex +
            "&pageSize=" +
            pageSize
        );
      } else {
        data = await queryApi.get(
          "userques/bygrouppage/-1" +
            "?page=" +
            pageIndex +
            "&pageSize=" +
            pageSize
        );
      }
      console.log(user.role + "查找问卷成功---", data.data.status);
      // console.log(data.data.data[1].userproblem);
      let myquesArr = data.data.data;
      dispatch({ type: "get_ques", payload: { myquesArr: myquesArr } });
      // console.log("第", pageIndex, "页第一份---", myquesArr[0].title);
      setPage(pageIndex);
      setPageLen(data.data.dataLen);
      let t_village = JSON.parse(JSON.stringify(villageArr));
      for (let i = 0; i < myquesArr.length; i++) {
        let villageCode = myquesArr[i].body[0].contents[1].answer.trim();
        if (villageCode != "" && myquesArr[i].state != 0) {
          if (t_village.indexOf(villageCode) == -1) {
            t_village.push(villageCode);
          }
        }
      }
      setVillageArr(JSON.parse(JSON.stringify(t_village)));
      // console.log("村代码数组---", villageArr);
      setOpinionsLoading("end");
    } catch (error) {
      setOpinionsLoading("error");
      console.log(user.role + "找不到问卷---", error);
    }
  };

  const addReply = async (quesIndex, replyDetail) => {
    const user = store.getState().authR.user;
    let replyArr = {
      ...GroupQuesData[quesIndex].opinions,
      opinions: [
        ...GroupQuesData[quesIndex].opinions.opinions,
        {
          ...replyDetail,
          publisher: user.name,
        },
      ],
    };
    try {
      await queryApi.patch("opinion/" + replyArr._id, replyArr);
      let AllData = await queryApi.get("opinion/" + replyArr._id);
      console.log("添加评论成功---", AllData.data.data);
      dispatch({
        type: "edit_opinions",
        payload: { quesIndex: quesIndex, opinions: AllData.data.data },
      });
    } catch (error) {
      console.log("添加评论失败---", error);
    }
  };

  // 审核问卷
  const examineQues = async (quesIndex, state, callback) => {
    try {
      let Ques = { ...GroupQuesData[quesIndex], state: state };
      let data = await queryApi.patch("userques/", {
        Ques: Ques,
        flag: "edit",
      });
      console.log("审核成功---", data.data.status);
      dispatch({ type: "edit_state", payload: { quesIndex, Ques } });
      callback(true);
    } catch (error) {
      callback(false);
      console.log("审核失败---", error);
    }
  };

  // 导出Excel
  const generateExcel = (ExcelData) => {
    // 工作簿
    let wb = XLSX.utils.book_new();
    // 工作表
    let ws;

    for (let i = 0; i < ExcelData.length; i++) {
      if (ExcelData[i].length > 2) {
        // console.log(ExcelData[i]);
        ws = XLSX.utils.aoa_to_sheet(ExcelData[i]);
        XLSX.utils.book_append_sheet(wb, ws, typeOptions[i], true);
      }
    }

    // generate the base64 content of my workbook
    const base64 = XLSX.write(wb, { type: "base64" });
    console.log(
      "FileSystem.documentDirectory---",
      FileSystem.documentDirectory
    );
    const filename = FileSystem.documentDirectory + "问卷.xlsx";
    FileSystem.writeAsStringAsync(filename, base64, {
      encoding: FileSystem.EncodingType.Base64,
    }).then(() => {
      Sharing.shareAsync(filename);
    });
  };

  // 获取导出Excel的数据
  const exportExcel = async (quesArr, ExcelTitle) => {
    try {
      let idArr = [];
      for (let i = 0; i < quesArr.length; i++) {
        if (quesArr[i]) {
          idArr.push(GroupQuesData[i]._id);
        }
      }
      let data = await queryApi.get("userques/exceldata", {
        params: { idArr: idArr },
      });
      console.log("获取Excel表数据成功---", data.data.status);
      generateExcel(data.data.data);
    } catch (error) {
      Alert.alert("导出问卷失败");
      console.log("导出Excel表失败---", error);
    }
  };

  const exportAllExcel = async () => {
    const user = store.getState().authR.user;
    let group;
    if (user.role == "admin") {
      group = user.group;
      try {
        let data = await queryApi.get("userques/generateexcel/" + group);
        Alert.alert("文件生成中，请稍后查看");
      } catch (error) {
        Alert.alert("导出失败");
        console.log("导出" + group + "组全部问卷失败---", error);
      }
    } else {
      group = "-1";
      Alert.alert("审核员不开放此功能");
    }
  };

  const getExcelByGroup = async () => {
    const user = store.getState().authR.user;
    let group;
    if (user.role == "admin") {
      group = user.group;
      try {
        let data = await queryApi.get("excel/group/" + group);
        if (data.data.data.length == 0) {
          Alert.alert("暂无已生成的文件");
        } else {
          if (data.data.data[0].state == "success") {
            Clipboard.setString(serverUrl + "" + data.data.data[0].excelurl);
            Alert.alert(
              "文件地址已复制到剪切板",
              serverUrl + "" + data.data.data[0].excelurl
            );
          } else {
            Alert.alert("文件生成出错了 ", data.data.data[0].excelurl);
          }
        }
      } catch (error) {
        console.log("下载失败---", error);
        Alert.alert("找不到地址");
      }
    } else {
      group = "-1";
      Alert.alert("审核员不开放此功能");
    }
  };

  return (
    <OpinionsContext.Provider
      value={{
        opinionsLoading,
        GroupQuesData,
        villageArr,
        getGroupQues,
        addReply,
        examineQues,
        exportExcel,
        exportAllExcel,
        getExcelByGroup,
        pageLen,
      }}
    >
      {children}
    </OpinionsContext.Provider>
  );
};

export default OpinionsContext;
